﻿
using B.MESUI.Login.BasicData_UI.BasicData;
using B.MESUI.Login.EquipmentManagement.DeviceLedgerService;
using B.MESUI.Login.EquipmentManagement.DTO;
using B.MESUI.Login.WorkflowCore.Form;
using DevExpress.XtraEditors;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WorkflowCore2210A.Application.Dto;
using WorkflowCore2210A.Application.Dto.Output;

namespace B.MESUI.Login.WorkflowCore.Definition
{
    public partial class ShowDefinition : DevExpress.XtraEditors.XtraForm
    {

        private readonly DeviceGridPanel devicePanel;
        public ShowDefinition()
        {
            InitializeComponent();
            // 1. 创建控件实例
            devicePanel = new DeviceGridPanel();
            devicePanel.Dock = DockStyle.Fill;
            // 2. 加入到主窗体的某个Panel或直接加到this.Controls
            this.Controls.Add(devicePanel);

            // 4. 绑定事件
            devicePanel.AddClicked += (s, e) => { /* 新增逻辑 */
               var addForm = new AddDefinition();
                addForm.ShowDialog();
                if(addForm.DialogResult == DialogResult.OK) 
                {
                     FlushData();
                }
            };
            devicePanel.ExportClicked +=async (s, e) => { /* 设计表单逻辑 */
                var FormFields=new List<FormField>();
                var ids = devicePanel.GetSelectedIdsString();
                var lenth = ids.Split(',').Count();
                if (ids=="") 
                {
                    MessageBox.Show("请选择要设计表单的流程！");
                    return;
                }
                if (lenth > 1)
                {
                    MessageBox.Show("请选择一条数据进行操作！");
                    return;
                }
                using (var client = new HttpClient())
                {
                    var url = $"{BaseUrl.WorkflowUrl}Workflow/GetFormTemplate?definitionModelId={ids}";
                    var response = await client.GetAsync(url);
                    response.EnsureSuccessStatusCode();
                    var json = await response.Content.ReadAsStringAsync();
                    var result = JsonConvert.DeserializeObject<ApiResult<FormTemplateOutput>>(json);
                    FormFields=result.Data.FormFields;
                }
               

                var addForm = new DesignForm(ids,FormFields);
                addForm.ShowDialog();
                if (addForm.DialogResult == DialogResult.OK)
                {
                    FlushData();
                }
            };
            devicePanel.DeleteClicked +=  (s, e) =>
            {
                /* 删除逻辑 */
                var ids = devicePanel.GetSelectedIdsString();

                if (ids.Length == 0) { MessageBox.Show("请选择要删除的数据！！！"); }
                else
                {
                    //使用httpclint调用自己的后端批量删除
                    //删除后刷新FlushData();
                }
            };
            //发起审批事件
            devicePanel.EditClicked += async(s, e) => { 
                var formFields = new List<FormField>();
                using (var client = new HttpClient()) 
                {
                    var url= $"{BaseUrl.WorkflowUrl}Workflow/GetFormTemplate?definitionModelId={e}";
                    var response = await client.GetAsync(url);
                    response.EnsureSuccessStatusCode();
                    var json = await response.Content.ReadAsStringAsync();
                    var result = JsonConvert.DeserializeObject<ApiResult<FormTemplateOutput>>(json);
                    if (result.Message == "暂无数据") 
                    {
                        MessageBox.Show("请先设计表单！");
                        return;
                    }
                    formFields = result.Data.FormFields;
                }
                var selectedRow = devicePanel.gridView.GetFocusedRow();
                var workflowDefinition = selectedRow as WorkflowDefinitionOutput;
                var startDefinition = new StartDefinition(formFields, workflowDefinition);
                startDefinition.ShowDialog();
                if (startDefinition.DialogResult == DialogResult.OK)
                {
                    FlushData();
                }
            
            };

            // 查询事件
            devicePanel.SearchClicked += async (s, e) =>
            {
                // 获取查询条件
                var searchConditions = devicePanel.GetSearchConditions();
                // 重置到第一页进行查询
                var result = await GetDeviceTypeListAsync(1, devicePanel.PageSize, searchConditions);
                BindDataSetColumns(result.Data);
                devicePanel.SetPageInfo(1, devicePanel.PageSize, result.TotalCount);
            };
            // 重置事件
            devicePanel.ResetClicked += async (s, e) =>
            {
                // 重置查询条件
                devicePanel.ResetSearchConditions();
                // 重新加载第一页数据
                var result = await GetDeviceTypeListAsync(1, devicePanel.PageSize);
                BindDataSetColumns(result.Data);
                devicePanel.SetPageInfo(1, devicePanel.PageSize, result.TotalCount);
            };

            // 5. 分页事件
            devicePanel.OnPageChanged += async (pageIndex, pageSize) =>
            {
                // 获取当前查询条件
                var searchConditions = devicePanel.GetSearchConditions();
                // 这里调用你的后端API
                var result = await GetDeviceTypeListAsync(pageIndex, pageSize, searchConditions); // 你的API
                BindDataSetColumns(result.Data);
                devicePanel.SetPageInfo(pageIndex, pageSize, result.TotalCount);
            };
        }



        /// <summary>
        /// 绑定数据、隐藏指定列、设置列名方法
        /// </summary>
        private void BindDataSetColumns(List<WorkflowDefinitionOutput> data)
        {
            // 需要隐藏的列名
            var hideColumnNames = new[] { "IsDeleted", "AnotherColumn", "UpdateUserName","UpdateTime","Id","ID" };

            // 列名映射
            var columnCaptions = new Dictionary<string, string>
            {
                //{ "Id", "设备编号" },
                // 其他字段...
                { "DefinitionId", "流程设计的标识" },
                { "Version", "版本号" },
                { "Title", "流程设计的标题" },
                { "UpdateUserName", "修改人" },
                { "UpdateTime", "修改时间" },
            };

            devicePanel.SetDataSource(data);
            foreach (var colName in hideColumnNames)
            {
                var col = devicePanel.gridView.Columns[colName];
                if (col != null)
                    col.Visible = false;
            }
            devicePanel.SetColumnCaptions(columnCaptions);

/*            // 隐藏多选框（假设是第一列）
            devicePanel.gridView.OptionsSelection.MultiSelect = false;*/

            // 设置列自动填充
            devicePanel.gridView.OptionsView.ColumnAutoWidth = true;

            // 遍历所有列，找到类型为按钮的列
            foreach (DevExpress.XtraGrid.Columns.GridColumn col in devicePanel.gridView.Columns)
            {
                if (col.ColumnEdit is DevExpress.XtraEditors.Repository.RepositoryItemButtonEdit btnEdit)
                {
                    btnEdit.Buttons[0].Caption = "发起审批"; // 比如“查看详情”
                }
            }

        }
        // 获取显示值方法，实际根据你的后端API来写
        private async Task<(List<WorkflowDefinitionOutput> Data, int TotalCount)> GetDeviceTypeListAsync(int pageIndex, int pageSize, Dictionary<string, object> searchConditions = null)
        {
            // 调用后端接口，返回数据和总数
            using (var client = new HttpClient())
            {
                // 构建查询参数
                var queryParams = new List<string>
        {
            $"PageIndex={pageIndex}",
            $"PageSize={pageSize}"
        };

                // 添加查询条件
                if (searchConditions != null && searchConditions.Count > 0)
                {
                    foreach (var condition in searchConditions)
                    {
                        if (condition.Value != null)
                        {
                            string value = condition.Value.ToString();
                            if (!string.IsNullOrEmpty(value))
                            {
                                // 根据值类型进行不同的处理
                                if (condition.Value is DateTime dateTime)
                                {
                                    value = dateTime.ToString("yyyy-MM-dd");
                                }
                                else if (condition.Value is bool boolValue)
                                {
                                    value = boolValue.ToString().ToLower();
                                }

                                queryParams.Add($"{condition.Key}={Uri.EscapeDataString(value)}");
                            }
                        }
                    }
                }

                string queryString = string.Join("&", queryParams);
                //改成自己的接口
                string url = $"{BaseUrl.WorkflowUrl}Workflow/GetWorkflowDefinitionList?{queryString}";
                //替换为自己的传值方式"Get","Post","Put","Delete"
                var response = await client.GetAsync(url);
                response.EnsureSuccessStatusCode();
                var json = await response.Content.ReadAsStringAsync();
                //替换为你自己的数据模型
                var result = JsonConvert.DeserializeObject<WorkflowCore2210A.Application.Dto.ApiPaging<WorkflowDefinitionOutput>>(json);
                foreach (var item in result.PageList) 
                {
                    item.Id=item.ID;
                }
                return (result.PageList, result.TotalCount);
            }
        }
        /// <summary>
        /// 刷新数据
        /// </summary>
        private async void FlushData()
        {
            // 首次加载第一页
            var result = await GetDeviceTypeListAsync(1, 20);//默认1页20条
            BindDataSetColumns(result.Data);
            devicePanel.SetPageInfo(1, 20, result.TotalCount);
        }

        private void ShowDefinition_Load(object sender, EventArgs e)
        {
            devicePanel.btnExport.Text = "设计表单";
            devicePanel.btnExport.Width = 130;
            devicePanel.btnDelete.Visible= false;
            // 首次加载第一页
            FlushData();

        }
    }
}